<?php

namespace app\index\controller;

use app\data\model\ActOrder;
use app\index\service\LoginUserService;
use Endroid\QrCode\QrCode;

class UserTicket extends BaseController
{   

    protected function initialize()
    {
        parent::initialize();
        $this->needLogin();
    }

    public function index()
    {
        $query = request()->get();
        $where = [];
        $where[]  = ['buy_user_id','=',LoginUserService::get('id')];
        if(!empty($query['status'])){
            $where[] =  ['status','=',$query['status']];
        }else{
            $query['status']  = 4;
        }
        $this->tickets = ActOrder::where($where)->append(['ticket_info', 'activity_info'])->order('id desc')->limit(20)->select();
      
        $this->query  = $query;
        // $this->page   = $this->tickets->render();
        $this->statusMapping = [
            ['code' => 1, 'text' => '已创建','count' => 0],
            ['code' => 2, 'text' => '已支付','count' => 0],
            ['code' => 3, 'text' => '待审核','count' => 0],
            ['code' => 4, 'text' => '已出票','count' => 0],
            ['code' => 5, 'text' => '已退款','count' => 0],
            ['code' => 6, 'text' => '无效','count' => 0]
            // 添加更多状态映射根据您的需求
        ];
        foreach ($this->statusMapping as $key => &$value) {
            $value['count'] = ActOrder::where('buy_user_id', LoginUserService::get('id'))->where('status',$value['code'])->count();
        }
        $this->fetch();
    }

    public function detail($id)
    {
        $this->order = ActOrder::where('id', $id)->where('buy_user_id', LoginUserService::get('id'))->find();
        if (empty($this->order)) {
            $this->error('门票不存在！');
        }
        $this->order->append(['ticket_info', 'activity_info', 'status_name']);
        $qrCode = new QrCode($this->order->sn);
        // 内容区域宽高,默认为300
        $qrCode->setSize(300);
        // 外边距大小,默认为10
        $qrCode->setPadding(10);
        // 设置二维码颜色,默认为黑色
        $qrCode->setForegroundColor(['r' => 0, 'g' => 0, 'b' => 0, 'a' => 0]);
        // 设置二维码背景色,默认为白色
        $qrCode->setBackgroundColor(['r' => 255, 'g' => 255, 'b' => 255, 'a' => 0]);

        $this->qr = $qrCode->getDataUri();
        $this->fetch();
    }
}